def triplet_sum_close_to_target(arr, target_sum):
  arr.sort()
  temp_target = 0;
  left = 0
  right = len(arr)-1
  smallest_sum = arr[right]*3

  for i in range(len(arr)-2):
    left  = i + 1
    right = len(arr)-1
    while(left < right):
      temp_sum = arr[i]+arr[left]+arr[right]
      if((target_sum - temp_sum) == 0):
        return temp_sum
      if abs(target_sum - temp_sum) < abs(target_sum - smallest_sum):
        smallest_sum = temp_sum
      elif (abs(target_sum - temp_sum) == abs(target_sum - smallest_sum)) and (temp_sum<smallest_sum):
        smallest_sum = temp_sum
      
      if (target_sum - temp_sum) > 0:
        left += 1
      else:
        right -= 1
  return smallest_sum

def main():
  print(triplet_sum_close_to_target([-2, 0, 1, 2], 2))
  print(triplet_sum_close_to_target([-3, -1, 1, 2], 1))
  print(triplet_sum_close_to_target([1, 0, 1, 1], 100))


main()